"use client"
import Custom from '@/components/layouts/custom'
import Image from 'next/image'
import mangosteen from 'public/icons/user/mangosteen.svg?url'
import { Form, Input, Button, Toast } from 'antd-mobile'
import styles from '@/app/login/login.module.scss'
import { cFetch } from '@/lib/Http'
import {useBool} from '@/hooks/useBool'
import { useState, useEffect, useRef } from 'react'
import { signIn} from "next-auth/react";
import {useSearchParams, useRouter} from 'next/navigation'
export default function Login(){
  const [form] = Form.useForm()
  const email = useSearchParams().get('email')
  const code = useSearchParams().get('code')
  const defaultValueObj={ email: '', code: '' }

  if(email){
    defaultValueObj.email = email
  }
  if(code){
    defaultValueObj.code = code
  }
  
  useEffect(() => {
    form.setFieldsValue(defaultValueObj)
  }, [])

  let [count, setCount] = useState(5)
  const timerRef = useRef<NodeJS.Timeout>();
  const startCountDown = () => {
    validCodeBtnDisabled()
    timerRef.current = setInterval(() => {
      setCount((prevCount) => prevCount - 1);
    }, 1000)
  }
  useEffect(() => {
    return () => {
      if(count <= 0){
        clearInterval(timerRef.current);
        validCodeBtnUse()
        setCount(5)
      }
    };
  }, [count])

  const {state: validCodeBtnState,on: validCodeBtnDisabled, off: validCodeBtnUse} = useBool(false)
  /**
   * @name 获取验证码
   */
  const getValidateCode = ()=>{
    startCountDown()
    form.validateFields(['email']).then(formData=>{
      const {email} = formData
      cFetch.post<string>('/sendValidateCode', { email }, { _autoLoading: true }).then(res=>{
        Toast.show({ icon: 'success', content: res })
      })
    }).catch(error=>{
      validCodeBtnUse()
      const errMsg = error.errorFields?.[1]?.errors?.[0] ?? '请完善表单信息！'
      Toast.show({ icon: 'fail', content: errMsg })
    })
  }

  const returnTo = useSearchParams().get('return_to')
  const router = useRouter()
  const onSubmit = async() => {
    const {email,code:password} = form.getFieldsValue()
    const callbackUrl = returnTo ? returnTo : '/welcome'
    // signIn('credentials', { email, password, callbackUrl: `${window.location.origin}${callbackUrl}` })
    const res = await signIn('credentials', { email, password,redirect: false,})
    if(res){
      if(res.ok){
        Toast.show({ icon: 'success', content: '登录成功！', duration: 700})
        setTimeout(() => {
          router.push(callbackUrl)
        } , 800)
      }else{
        Toast.show({ icon: 'fail', content: res.error })
      }
    }else{
      Toast.show({ icon: 'fail', content: '登录失败！' })
    }
  }
  return (
    <Custom header={<div className="text-white text-2xl"> <h3>登录</h3> </div>} >
      <section className="logoSec flex flex-col justify-center items-center gap-3 pt-[42px]">
        <Image src={mangosteen} alt="Logo" width={64} height={68} className="h-[68px] w-[64px]"/>
        <h3 className="text-[32px] font-bold text-[var(--app-name-color)]">蓝莓记账</h3>
      </section>
      <Form
        form={form}
        layout='horizontal'
        className={`${styles.perfectForm} pt-8`}
        style={{'--prefix-width':'5em'}}
        mode="card"
        footer={
          <Button block type='submit' color='primary' onClick={onSubmit}>
            登录
          </Button>
        }
      >
        <Form.Item name='email' label='邮箱地址' rules={[
          { required: true, message: '请输入邮箱地址' },
          { type: 'email', message: '请输入有效的邮箱!' }
          ]}>
          <Input placeholder='邮箱地址' />
        </Form.Item>
        <Form.Item name='code' label='验证码' rules={[{ required: true, message: '请输入验证码' }]} 
          extra={
            <div className={styles.extraPart}>
              <Button color='primary' fill='none' disabled={validCodeBtnState} onClick={getValidateCode}>
                {validCodeBtnState?`${count}秒后可重新发送`:'发送验证码'}
              </Button>
            </div>
          }>
          <Input placeholder='验证码' maxLength={6}/>
        </Form.Item>
      </Form>
    </Custom>
  )
}